package com.freeter.XMLUtil;

import java.io.PrintWriter;

import com.freeter.model.xml.Address;
import com.freeter.model.xml.Person;
import com.thoughtworks.xstream.XStream;

/** 
* @author  作者 E-mail: 
* @date 创建时间：2018年1月26日 上午11:46:54 
* @version 1.0 
* @parameter  
* @since  
* @return  
*/
public class Test {
	public static String xmlFile = "xmlfile";
	 public static void main(String[] as) throws Exception{
		 
		 String root = Thread.currentThread().getContextClassLoader().getResource(xmlFile).getPath();
		 
			Person person = new Person();
			person.setName("huyun3424");
			person.setPhoneNuber(1385546);
			Address address1 = new Address();
			address1.setHouseNo(6666);
			address1.setStreet("234");
			Address address2 = new Address();
			address2.setHouseNo(234234);
			address2.setStreet("丰台");
			person.getAddresses().add(address1);
			person.getAddresses().add(address2);
			String pxml = toXML(person);
			System.out.println(pxml);
			 
			///System.out.println(p);

			toXMLFile(person, root + "/data.xml");
	 }
	 
	 public static String toXML(Object obj) {
			XStream xstream = new XStream();

			xstream.processAnnotations(obj.getClass()); // 通过注解方式的，一定要有这句话

			return xstream.toXML(obj);
		}
	 
	 /*
		 * PrintWriter无追加模式，若写入已有文件，将清空原文件，重新写入；
		 */
		public static void toXMLFile(Object obj, String path) throws Exception {
			XStream xstream = new XStream();

			xstream.processAnnotations(obj.getClass()); // 通过注解方式的，一定要有这句话
			PrintWriter pw = new PrintWriter(path, "utf-8");
			xstream.toXML(obj, pw);
		}
}
